import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import {
  fetchDemandList,
  operateDemand,
  cancelOperateDemand,
  operateCollect,
  operateCancelCollect,
} from '@/business/services/demand/demand';

/**
 * @description 需求列表
 * @author Shawn
 */

type RequestFunction = (
  pageParams: PageParams,
  tag?: string,
  orderField?: string,
  cityCode?: string,
  isAppend?: boolean,
) => Promise<void>;

export type RequestFunction2 = (
  demandId: string,
  type: string,
  status: string,
  tag?: string,
) => Promise<void>;

export type RequestFunction3 = (demandId: string, tag?: string) => Promise<void>;

type State = {
  // 需求列表
  demandList: any[];
  // 分页信息
  pageInfo: PageInfo;
  // 数据是否加载完成
  isDataLoaded: boolean;
  // 是否有更多数据
  hasMore: boolean;
};

type Actions = {
  // 获取需求列表
  getDemandList: RequestFunction;
  // 上拉加载/下拉刷新
  handlePullUpOrDown: RequestFunction;
  // 点赞、点踩
  handleLikeOrDislike: RequestFunction2;
  // 取消点赞、点踩
  handleCancelLikeOrDislike: RequestFunction2;
  // 收藏
  handleCollect: RequestFunction2;
  // 取消收藏
  handleCancelCollect: RequestFunction3;
};

const initialState: State = {
  // 需求列表
  demandList: [],
  // 分页信息
  pageInfo: {},
  // 数据是否加载完成
  isDataLoaded: true,
  // 是否有更多数据
  hasMore: true,
};

export const demandListStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取需求列表
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     */
    getDemandList: async (
      pageParams: PageParams,
      tag?: string,
      orderField?: string,
      cityCode?: string,
      isAppend = false,
    ) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        // Taro.showLoading({
        //   title: '加载中',
        // });
        const requestData = {
          ...pageParams,
          ...(tag ? { tag } : {}),
          ...(orderField ? { orderField } : {}),
          ...(cityCode ? { cityCode: cityCode === '00' ? '' : cityCode } : {}),
        };
        const result = await fetchDemandList(requestData);
        if (result.success) {
          set((state) => {
            if (isAppend) {
              state.demandList = [...state.demandList, ...result?.data];
            } else {
              state.demandList = result?.data;
            }
            state.pageInfo = {
              pageIndex: result?.current,
              pageSize: result?.pageSize,
              totalCount: result?.totalCount,
            };
            state.hasMore = result?.pageIndex * result?.pageSize < result?.totalCount;
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        // Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 上拉加载/下拉刷新
     * @param pageParams 分页
     */

    handlePullUpOrDown: async (
      pageParams: PageParams,
      tag?: string,
      orderField?: string,
      cityCode?: string,
      isAppend = true,
    ) => {
      const newPageInfo = { ...pageParams };
      await get().getDemandList(newPageInfo, tag, orderField, cityCode, isAppend);
    },

    /**
     * 点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleLikeOrDislike: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateDemand({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.demandList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'LIKE') {
                // 如果之前点踩了，先取消点踩
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                // 如果之前点赞了，先取消点赞
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleCancelLikeOrDislike: async (demandId: string, type: string, status: string) => {
      console.log('handleCancelLikeOrDislike', demandId, type, status);
      try {
        const result = await cancelOperateDemand({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.demandList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 收藏
     */
    handleCollect: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateCollect({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.demandList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消收藏
     */
    handleCancelCollect: async (demandId: string) => {
      try {
        const result = await operateCancelCollect({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.demandList.find((d) => d.id === demandId);
            if (item) {
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
              console.log('handleCancelCollect success');
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
  })),
);
